package splug.cjk;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import splug.cjk.packet.BBSCarPoolPacket;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MyWritingTab3 extends ListActivity implements OnItemClickListener{
	private String id;
	private ArrayList<Content> content;
	private ArrayList<BBSCarPoolContent> sub_content;
	private ContentAdapter m_adapter;
	private Button write;
	private Button search;
	private double latitude;
	private double longitude;

	/**
	 * 어댑터를 사용자 정의대로 오버라이딩 한 이너클래스
	 * @author jck
	 *
	 */
	private class ContentAdapter extends ArrayAdapter<Content> {

		private ArrayList<Content> items;

		public ContentAdapter(Context context, int textViewResourceId, ArrayList<Content> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.list_property, null);
			}
			Content p = items.get(position);
			if (p != null) {
				TextView tt = (TextView) v.findViewById(R.id.toptext);
				TextView bt = (TextView) v.findViewById(R.id.bottomtext);
				if (tt != null){
					tt.setText(p.getTitle());
				}
				if(bt != null){
					bt.setText("글쓴이: "+ p.getId());
				}
			}
			return v;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bbs_carpool_tab1);
		setTitle("태워주세요 게시판에 내가 쓴 글");

		Bundle b = this.getIntent().getExtras();
		id = String.valueOf(b.getString("ID"));
		
		write = (Button) findViewById(R.id.btn_carpool_tab1_write);
		search = (Button) findViewById(R.id.btn_carpool_tab1_search);
		
		write.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MyWritingTab3.this, BBSCarPoolTab1Write.class);
				Bundle b = new Bundle();
				b.putString("ID", id);
				intent.putExtras(b);
				startActivityForResult(intent, 1);
			}
		});
		
		search.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MyWritingTab3.this, BBSCarPoolTab1Search.class);
				Bundle b = new Bundle();
				b.putString("ID", id);
				intent.putExtras(b);
				b.putSerializable("TITLE", content);
				intent.putExtras(b);
				b.putSerializable("SUB", sub_content);
				intent.putExtras(b);
				startActivity(intent);
			}
		});
		
		/**
		 * 내가 작성한 태워주세요 게시물을 서버로부터 받아온다
		 */
		try {
			Socket socket = new Socket(LetsGoActivity.server_ip, 2007);
			
			InputStream is = socket.getInputStream();
			OutputStream os = socket.getOutputStream();
			
			OutputStreamWriter osw = new OutputStreamWriter(os);
			InputStreamReader isr = new InputStreamReader(is);
			
			osw.write(21);
			osw.flush();
			
			int ack = isr.read();
			
			if(ack == '1'){
				/**
				 * 내 ID를 서버로 전송
				 */
				ObjectOutputStream output = new ObjectOutputStream(os);
				BBSCarPoolPacket packet = new BBSCarPoolPacket(null, null, 0, id, null, null, null, null, null, null,0 ,0);
				output.writeObject(packet);
				
				/**
				 * 내 ID로 남긴 글의 목록을 받아옴
				 */
				ObjectInputStream input = new ObjectInputStream(is);
				packet = (BBSCarPoolPacket) input.readObject();
				
				content = packet.getContent();
				sub_content = packet.getSub_content();
			}
			else{
				Toast.makeText(MyWritingTab3.this, "네트워크 연결상대가 좋지 않습니다", Toast.LENGTH_SHORT).show();
				finish();
			}
			
			
		} catch (Exception e) {
			Toast.makeText(MyWritingTab3.this, "네트워크 연결상대가 좋지 않습니다", Toast.LENGTH_SHORT).show();
			finish();
		}

		m_adapter = new ContentAdapter(MyWritingTab3.this, R.layout.list_property, content);
		setListAdapter(m_adapter);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub

	}

	//리스트가 클릭되었을 때의 이벤트
	@Override
	protected void onListItemClick(ListView l, View v, int position, long aaa) {
		super.onListItemClick(l, v, position, aaa);

		Intent intent = new Intent(MyWritingTab3.this, BBSCarPoolTab2Content.class);
		Bundle b = new Bundle();
		b.putString("ID", id);
		b.putString("AUTHOR", content.get(position).getId());
		b.putInt("NUMBER", sub_content.get(position).getNumber());
		b.putString("CONTENT", sub_content.get(position).getContent());
		b.putString("TIME", sub_content.get(position).getTime());
		b.putString("START", sub_content.get(position).getStart());
		b.putString("FINISH", sub_content.get(position).getFinish());
		b.putString("DATE", sub_content.get(position).getDate());
		intent.putExtras(b);
		startActivity(intent);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(resultCode == RESULT_OK){
			if(requestCode == 1){
				String tmp_title = data.getStringExtra("TITLE");
				String tmp_content = data.getStringExtra("CONTENT");
				String tmp_start = data.getStringExtra("START");
				String tmp_finish = data.getStringExtra("FINISH");
				String tmp_time = data.getStringExtra("TIME");
				
				/*
				 * 순방향 지오코딩
				 * 입력한 출발지를 이용해서 지도의 위도와 경도를 받아온다
				 */
				try {
					Geocoder coder = new Geocoder(getApplicationContext(), Locale.KOREA);
					List<Address> geoResult = coder.getFromLocationName(tmp_start, 1);
					Iterator<Address> locations = geoResult.iterator();
					
					while(locations.hasNext()){
						Address loc = locations.next();
						latitude = loc.getLatitude();
						longitude = loc.getLongitude();
					}
//					Toast.makeText(BBSCarPoolTab1.this, str, Toast.LENGTH_LONG).show();
					
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				
				//게시물이 쓰여진 시간을 스트링에 저장한다.
				Calendar myCalendar = Calendar.getInstance();
				String tmp_date = Integer.toString(myCalendar
						.get(Calendar.YEAR));
				tmp_date += "/"
						+ Integer.toString(myCalendar
								.get(Calendar.MONTH) + 1);
				tmp_date += "/"
						+ Integer.toString(myCalendar
								.get(Calendar.DAY_OF_MONTH));
				tmp_date += " "
						+ Integer.toString(myCalendar
								.get(Calendar.HOUR_OF_DAY));
				tmp_date += "시 "
						+ Integer.toString(myCalendar
								.get(Calendar.MINUTE)) + "분";
				
				try {
					Socket socket = new Socket(LetsGoActivity.server_ip, 2007);
					InputStream is = socket.getInputStream();
					OutputStream os = socket.getOutputStream();
					InputStreamReader isr = new InputStreamReader(is);
					OutputStreamWriter osw = new OutputStreamWriter(os);
					
					osw.write('6');
					osw.flush();
					
					int ack = isr.read();
					
					if(ack == '1'){
						BBSCarPoolPacket packet = new BBSCarPoolPacket(null, null, 0, id, tmp_title, tmp_start, tmp_finish, tmp_time, 
								tmp_content, tmp_date, latitude, longitude);
						ObjectOutputStream output = new ObjectOutputStream(os);
						output.writeObject(packet);
						
						ack = isr.read();
						
						if(ack == '1'){
							Toast.makeText(MyWritingTab3.this, "글쓰기 완료!", Toast.LENGTH_SHORT).show();
						}
						else{
							Toast.makeText(MyWritingTab3.this, "네트워크 상태가 불안정합니다", Toast.LENGTH_SHORT).show();
						}
						
					}
					else{
						Toast.makeText(MyWritingTab3.this, "네트워크 상태가 불안정합니다", Toast.LENGTH_SHORT).show();
						finish();
					}
					
					
				} catch (Exception e) {
					Toast.makeText(MyWritingTab3.this, "네트워크 상태가 불안정합니다", Toast.LENGTH_SHORT).show();
					finish();
				}
				

				/**
				 * 글의 목록을 다시 불러옴
				 */
				try {
					Socket socket = new Socket(LetsGoActivity.server_ip, 2007);
					
					InputStream is = socket.getInputStream();
					OutputStream os = socket.getOutputStream();
					
					OutputStreamWriter osw = new OutputStreamWriter(os);
					InputStreamReader isr = new InputStreamReader(is);
					
					osw.write(21);
					osw.flush();
					
					int ack = isr.read();
					
					if(ack == '1'){
						/**
						 * 내 ID를 서버로 전송
						 */
						ObjectOutputStream output = new ObjectOutputStream(os);
						BBSCarPoolPacket packet = new BBSCarPoolPacket(null, null, 0, id, null, null, null, null, null, null, 0, 0);
						output.writeObject(packet);
						
						/**
						 * 내 ID로 남긴 글의 목록을 받아옴
						 */
						ObjectInputStream input = new ObjectInputStream(is);
						packet = (BBSCarPoolPacket) input.readObject();
						
						content = packet.getContent();
						sub_content = packet.getSub_content();
					}
					else{
						Toast.makeText(MyWritingTab3.this, "네트워크 연결상대가 좋지 않습니다", Toast.LENGTH_SHORT).show();
						finish();
					}
					
					
				} catch (Exception e) {
					Toast.makeText(MyWritingTab3.this, "네트워크 연결상대가 좋지 않습니다", Toast.LENGTH_SHORT).show();
					finish();
				}
				
				m_adapter = new ContentAdapter(this, R.layout.list_property, content);
				setListAdapter(m_adapter);
				m_adapter.notifyDataSetChanged();
			}
		}
	}

}
